﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace Common.Json
{
    /// <summary>
    /// 长整数类型序列化为字符串。长整数类型在前端js解析会损失精度，所以转成字符串类型
    /// </summary>
    public class LongToStringConverter : JsonConverter
    {
        /// <summary>
        /// 是否适用转换
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public override bool CanConvert(Type objectType)
        {
            return typeof(long) == objectType || typeof(long?) == objectType;
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
        {
            object currentValue = reader.Value;
            if (currentValue == null || string.IsNullOrEmpty(currentValue.ToString()))
            {
                return objectType == typeof(long?) ? (object)null : 0L;
            }
            if (currentValue.GetType() == typeof(string))
            {
                return long.Parse(currentValue.ToString());
            }
            return currentValue;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
        {
            writer.WriteValue(value?.ToString());
        }
    }
}
